var Koa = require('koa');
var Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const fs = require("fs");
const jwt = require("jsonwebtoken")
// var ip = require('ip');
// var myip = ip.address(); 
// var http = require('http');
// http.createServer(function(req,res){
//     res.writeHead(200,{'Content-Type':'text/plain'});
//     res.end('Hello Aliyun Node.js,hah\n');
// }).listen(80,"0.0.0.0");

//加密字符串
const server = "server";

var app = new Koa();
var router = new Router({
	
});

const homeData = require('./datas/home.json')
const searchData = require('./datas/search.json')
const detailData = require('./datas/detail.json')
const userInfoData = require('./datas/user.json')
const shopCartData = require('./datas/shopCart.json')

//获取首页数据
router.get('/getHomeData', (ctx, next) => {
	console.log('请求首页数据')
	ctx.body = {
		code: 200,
		data: homeData
	}
});
//获取搜索列表数据
router.get('/getSearchData', (ctx, next) => {
	console.log('请求搜索数据')
	ctx.body = {
		code: 200,
		data: searchData
	}
});
//获取商品详情数据
router.post('/getGoodsDetailData', async (ctx, next) => {
	console.log('请求商品详情数据')
	const goodsId = await ctx.request.body.id
	let goodsDetail = {}
	detailData.forEach(item => {
		if (item.id === goodsId) {
			goodsDetail = item
		}
	})
	ctx.body = {
		code: 200,
		data: goodsDetail
	}
});
//注册接口
router.post('/register', async (ctx, next) => {
	const currentRequest = await ctx.request;
	const {
		phone,
		password
	} = currentRequest.body;
	const userList = userInfoData;
	console.log(userInfoData)
	const isContain = userList.some(item => {
		return item.phone === phone;
	})
	if (!isContain) {
		const userObj = {
			phone,
			password,
			token: getToken({
				phone,
				password
			})
		}
		userInfoData.push(userObj);
		fs.writeFileSync("./datas/user.json", JSON.stringify(userInfoData))
		ctx.body = {
			code: 200,
			message: "注册成功"
		}
	} else {
		ctx.body = {
			code: 201,
			message: "账户已存在"
		}
	}
});
//登录接口
router.post('/login', async (ctx) => {
	const currentRequest = await ctx.request;
	const {
		phone,
		password
	} = currentRequest.body;
	console.log(phone, password);
	const userList = userInfoData;
	let token = ""
	const isContain = userList.some(item => {
		console.log(item.phone,item.password);
		if (item.phone === phone && item.password === password) {
			token = item.token;
			return true;
		}
	})
	if (isContain) {
		ctx.body = {
			code: 200,
			data: {
				token
			},
			message: "登录成功"
		}
	} else {
		ctx.body = {
			code: 201,
			message: "账户或密码错误"
		}
	}
})
//退出登录
router.get('/logout', (ctx, next) => {
	const currentRequest = ctx.request;
	ctx.body = {
		code: 200,
		message: "退出成功"
	}
});
//获取购物车列表
router.get('/getShopCartLst', (ctx, next) => {
	const currentRequest = ctx.request;
	const shopCartList = getShopCartList(currentRequest);
	ctx.body = {
		code: 200,
		data: shopCartList,
		message: "成功"
	}
});
//添加商品到购物车
router.post('/addGoodsToShopCart', async (ctx) => {
	const currentRequest = await ctx.request;
	addGoods(currentRequest);
	ctx.body = {
		code: 200,
		message: "添加成功"
	}
})
//修改购物车商品数量	
router.post('/updateGoodsCount', async (ctx) => {
	const currentRequest = await ctx.request;
	getUpdateGoodsCount(currentRequest);
	ctx.body = {
		code: 200,
		message: "修改成功"
	}
});
//删除购物车商品	
router.post('/deleteGoods', async (ctx) => {
	const currentRequest = await ctx.request;
	getDeleteGoods(currentRequest);
	ctx.body = {
		code: 200,
		message: "删除成功"
	}
});
//生成token
function getToken(payload = {}) {
	return jwt.sign(payload, server, {
		expiresIn: "1h"
	});
}

app
	.use(bodyParser())
	.use(router.allowedMethods())
	.use(router.routes())
app.listen("3001", (err) => {
	if (!err) {
		console.log("http://localhost:3001");
		// console.log(myip);
	} else {
		console.log("失败");
	}
})


//逻辑函数
//添加商品
function addGoods(currentRequest){
	const {
		id
	} = currentRequest.body
	console.log(id)
	const {
		token
	} = currentRequest.header;
	const shopCartList = shopCartData;
	const searchList = searchData.searchList;
	let currentUserCart = {};
	let currentUserGoods = {};
	const isHaveUser = shopCartList.some(item => {
		if (item.token === token) {
			currentUserCart = item;
			return true;
		}
	})
	if (isHaveUser) {
		console.log('-----')
		const isHaveGoods = currentUserCart.goodsList.some(item => {
			console.log(item)
			if (item.goods.id === id) {
				currentUserGoods = item;
				return true;
			}
		});
		if (isHaveGoods) {
			console.log(currentUserGoods);
			currentUserGoods.count += 1;
		} else {
			searchList.forEach(item => {
				if (item.id === id) {
					currentUserGoods = {
						goods: item,
						count: 1
					}
				}
			})
			currentUserCart.goodsList.push(currentUserGoods);
		}
	} else {
		searchList.forEach(item => {
			if (item.id === id) {
				currentUserGoods = {
					goods: item,
					count: 1
				}
			}
		})
		currentUserCart = {
			token,
			goodsList: [currentUserGoods]
		}
	}
	if(isHaveUser){
		shopCartData.forEach(item => {
			if(item.token === token){
				item = currentUserCart;
			}
		})
	}else{
		shopCartData.push(currentUserCart);
	}
	
	fs.writeFileSync("./datas/shopCart.json", JSON.stringify(shopCartData))
}
//返回购物列表
function getShopCartList(currentRequest){
	const {
		token
	} = currentRequest.header;
	const shopCartList = shopCartData;
	let userShopCartList = []
	shopCartList.forEach(item => {
		if(item.token === token){
			userShopCartList = item.goodsList;
		}
	})
	return userShopCartList;
}
//修改购物车商品
function getUpdateGoodsCount(currentRequest){
	const {id, count} = currentRequest.body;
	const {
		token
	} = currentRequest.header;
	const shopCartList = shopCartData;
	let currentUserCart = {}
	shopCartList.forEach(item => {
		if(item.token === token){
			currentUserCart = item;
		}
	})
	currentUserCart.goodsList.forEach(item => {
		if(item.goods.id === id){
			item.count = count;
		}
	})
	shopCartData.forEach(item => {
		if(item.token === token){
			item = currentUserCart;
		}
	})
	fs.writeFileSync("./datas/shopCart.json", JSON.stringify(shopCartData))
}
//删除购物车商品
function getDeleteGoods(currentRequest){
	const ids = currentRequest.body.ids ? currentRequest.body.ids : [];
	const {
		token
	} = currentRequest.header;
	if(ids.length){
		ids.forEach(id => {
			shopCartData.forEach(userShopCart => {
				if(userShopCart.token === token){					
					userShopCart.goodsList = userShopCart.goodsList.filter(goods => {
						return goods.id === id;
					})
					console.log('-----',userShopCart);
				}
			})
		})
	}
	fs.writeFileSync("./datas/shopCart.json", JSON.stringify(shopCartData))
}
